package com.xxxx.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.xxxx.server.pojo.Menu;
import com.xxxx.server.pojo.MenuRole;
import com.xxxx.server.pojo.Role;
import com.xxxx.server.service.IMenuRoleService;
import com.xxxx.server.service.IMenuService;
import com.xxxx.server.service.IRoleService;
import com.xxxx.server.util.RespBean;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:王亚栋
 * @Date: 2023/6/18 下午1:16
 * @Version:1.0
 * 权限组
 */
@RestController
@RequestMapping("/system/basic/permiss")
public class PermissionController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IMenuRoleService menuRoleService;


    @ApiOperation(value = "获取所有角色")
    @GetMapping("/")
    public List<Role> getAllRoles(){

        return roleService.list();
    }

    @ApiOperation(value = "添加角色")
    @PostMapping("/")
    public RespBean addRole(@RequestBody Role role){

        if (!role.getName().startsWith("ROLE_")){

            role.setName("ROLE_" + role.getName());
        }

        if (roleService.save(role)) {

            return RespBean.success("添加角色成功！");
        }

        return RespBean.error("添加角色失败！");
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("/role/{id}")
    public RespBean deleteRole(@PathVariable("id") Integer roleId){

        if (roleService.removeById(roleId)) {

            return RespBean.success("删除角色成功！");
        }

        return RespBean.error("删除角色失败！");
    }

    @ApiOperation(value = "查询所有菜单")
    @GetMapping("/menus")
    public List<Menu> getAllMenus(){

        return menuService.getAllMenus();
    }

    @ApiOperation(value = "根据角色Id查询菜单Id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable Integer rid){

        QueryWrapper<MenuRole> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("rid",rid);

        //菜单ID
        List<Integer> mIds = menuRoleService.list(queryWrapper).stream().map(MenuRole::getMid).collect(Collectors.toList());

        return mIds;
    }

    @ApiOperation(value = "更新角色菜单")
    @PutMapping("/")
    public RespBean updateMenuRole(Integer rid,Integer[] mids){

        return menuRoleService.updateMenuRole(rid, mids);

    }
}
